﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsFormsApp2
{
    public partial class RegisterForm : Form
    {
        public RegisterForm()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            string uid = txtUsername.Text;
            string pwd = txtPassword.Text;
            string rePwd = txtRetryPwd.Text;

            bool hasUid = !string.IsNullOrEmpty(uid);
            bool hasPwd = !string.IsNullOrEmpty(pwd);
            bool eqPwd = pwd == rePwd;
            
            //连接数据库
            var conString = "server = .; uid = sa; pwd = seventeen111; database = CwordDB";
            SqlConnection connection = new SqlConnection(conString);
            connection.Open();
            SqlCommand command = new SqlCommand("select*from Users",connection);

            //DatsSet
            SqlDataAdapter dataAdapter = new SqlDataAdapter();
            dataAdapter.SelectCommand = command;
            DataSet dataSet = new DataSet();
            dataAdapter.Fill(dataSet);

            //判断该用户是否存在在数据库中
            if (uid == dataSet.Tables[0].Rows[0]["name"].ToString())
            {
                MessageBox.Show("用户已存在 请重新输入","系统提示");    
            } 
            else if (hasUid && hasPwd && eqPwd)
            {
                MessageBox.Show("注册成功","系统提示");
                this.Hide();
                //注册后加入数据库中
                command.CommandText = "insert into Users (name,password) values (@name,@password)";
                command.Parameters.AddWithValue("@name", uid);
                command.Parameters.AddWithValue("@password", pwd);
                command.ExecuteNonQuery();
            }
            connection.Close();

            //判断用户是否填写或密码是否一致
            if (txtUsername.Text.ToString().Trim() == "")
            {
                MessageBox.Show("用户名未填写 请重新输入", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                txtUsername.Focus();
            }
            if (txtPassword.Text.ToString().Trim() != rePwd)
            {
                MessageBox.Show("密码不一致，请重新输入", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }

        }

        private void button2_Click(object sender, EventArgs e)
        {
            this.Close();
        }


    }


    }


